package com.pur.zsms.common.beans;

import java.beans.PropertyEditorSupport;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.util.StringUtils;

public class DatePropertyEditorSupport extends PropertyEditorSupport {

	SimpleDateFormat dateFormat = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss.SSS");

	SimpleDateFormat dateFormat2 = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss.SSS");

	@Override
	public void setAsText(String text) throws IllegalArgumentException {
		if (!StringUtils.hasText(text)) {
			setValue(null);
		} else {

			if (text.length() == 4) {
				text += "-01-01 00:00:00.000";
			} else if (text.length() == 7) {
				text += "-01 00:00:00.000";
			} else if (text.length() == 10) {
				text += " 00:00:00.000";
			} else if (text.length() == 13) {
				text += ":00:00.000";
			} else if (text.length() == 16) {
				text += ":00.000";
			} else if (text.length() == 19) {
				text += ".000";
			}

			if (text.length() != 23) {
				throw new IllegalArgumentException(
						"Could not parse date: ["
								+ text
								+ "]! Just support formatter [yyyy] [yyyy-MM] [yyyy-MM-dd] [yyyy-MM-dd HH] [yyyy-MM-dd HH:mm] [yyyy-MM-dd HH:mm:ss] [yyyy-MM-dd HH:mm:ss.SSS]");
			}

			try {
				setValue(dateFormat.parse(text));
			} catch (ParseException ex) {
				throw new IllegalArgumentException("Could not parse date: "
						+ ex.getMessage(), ex);
			}
		}
	}

	/**
	 * Format the Date as String, using the specified DateFormat.
	 */
	@Override
	public String getAsText() {
		dateFormat2.setLenient(false);
		Date value = (Date) getValue();
		return (value != null ? dateFormat.format(value) : "");
	}
}
